var express = require("express")
var router = express.Router()
//导入用于生成JWT字符串的包
const jwt = require("jsonwebtoken")
//导入token的配置
const { tokenConfig } = require("../../config")
let { secretKey, expiresIn } = tokenConfig
//导入操作数据库的方法
let { getOne, getAll, exec } = require("../../db")
//用户注册
router.post("/users/register", async (req, res) => {
  //解析请求体数据
  let { username, password, type } = req.body
  //编写sql语句
  let sql = `insert into userinfo (username,password,type) values ('${username}','${password}','${type}')`
  try {
    let data = await exec(sql)
    res.send({
      code: 200,
      message: "用户注册成功",
      result: {
        id: data.insertId,
        username,
        password,
      },
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "用户名已占用",
      result: "",
    })
  }
})
//用户登录(生成token,用户状态改为上线)
router.post("/users/login", async (req, res) => {
  //解析请求体数据
  let { username, password } = req.body
  //编写sql语句
  let sql = `select * from userinfo where username='${username}' and password='${password}'`
  try {
    let data = await getOne(sql)
    if (data == null) {
      res.send({
        code: 201,
        message: "用户名或者密码错误",
        result: "",
      })
    } else if (data.deleted == 1) {
      res.send({
        code: 203,
        message: "用户已注销",
        result: "",
      })
    } else {
      //生成token
      let token = jwt.sign({ username }, secretKey, expiresIn)
      //将用户状态改为上线
      await exec(`update userinfo set onlinestatus=1 where id=${data.id}`)
      data = await getOne(`select * from userinfo where id=${data.id}`)
      console.log(data)
      res.send({
        code: 200,
        message: "登陆成功",
        token,
        result: data,
      })
    }
  } catch (error) {
    res.send({
      code: 202,
      message: "未知错误",
      result: "",
    })
  }
})
//验证token是否失效,过期
router.get("/users/verify", async (req, res) => {
  //从请求头获取token
  let token = req.headers.authorization
  try {
    // 验证token
    let validation = jwt.verify(token, secretKey)
    res.send({
      code: 200,
      message: "验证token成功",
      result: validation,
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "无效的token",
      result: "",
    })
  }
})
//查询单个用户
router.get("/users/one/:id", async (req, res) => {
  //解析id
  let { id } = req.params
  //编写sql语句
  let sql = `select * from userinfo where id=${id}`
  try {
    let data = await getOne(sql)
    if (data == null) {
      res.send({
        code: 201,
        message: "该用户不存在",
        result: "",
      })
    } else {
      res.send({
        code: 200,
        message: "查询单个用户成功",
        result: data,
      })
    }
  } catch (error) {
    res.send({
      code: 202,
      message: "查询单个用户失败",
      result: "",
    })
  }
})
//分页获取所有用户
router.get("/users/all", async (req, res) => {
  // 获取用户总数
  let { total } = await getOne(`select count(*) as total from userinfo`)
  // 解析请求体数据
  let { page, offset } = req.query
  //获取起始索引
  let index = (page - 1) * offset
  //编写sql语句
  let sql = `select * from userinfo order by deleted asc limit ${index},${offset}`
  try {
    let data = await getAll(sql)
    res.send({
      code: 200,
      message: "获取所有用户成功",
      result: { total, data },
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "获取所有用户失败",
      result: 0,
    })
  }
})
//分页获取所有交通部门用户
router.get("/users/traffic", async (req, res) => {
  // 获取用户总数
  let { total } = await getOne(
    `select count(*) as total from userinfo where type=1`
  )
  // 解析请求体数据
  let { page, offset } = req.query
  console.log(page, offset)
  //获取起始索引
  let index = (page - 1) * offset
  //编写sql语句
  let sql = `select * from userinfo where type=1 order by id desc limit ${index},${offset}`
  try {
    let data = await getAll(sql)
    res.send({
      code: 200,
      message: "获取所有交通部门用户成功",
      result: { total, data },
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "获取所有交通部门用户失败",
      result: 0,
    })
  }
})
//分页获取所有普通用户
router.get("/users/normal", async (req, res) => {
  // 获取用户总数
  let { total } = await getOne(
    `select count(*) as total from userinfo where type=0`
  )
  // 解析请求体数据
  let { page, offset } = req.query

  //获取起始索引
  let index = (page - 1) * offset
  //编写sql语句
  let sql = `select * from userinfo where type=0 order by id desc limit ${index},${offset}`
  try {
    let data = await getAll(sql)
    res.send({
      code: 200,
      message: "获取所有普通用户成功",
      result: { total, data },
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "获取所有普通用户失败",
      result: 0,
    })
  }
})
//修改单个用户信息(用户名,密码,类型)
router.put("/users/msg/:id", async (req, res) => {
  //解析id
  let { id } = req.params
  // 解析请求体数据
  let { username, password, type } = req.body
  // 编写sql语句
  let sql = `update userinfo set username='${username}',password='${password}',type=${type} where id=${id} `
  try {
    await exec(sql)
    res.send({
      code: 200,
      message: "修改用户信息成功",
      result: {
        id,
        username,
        password,
      },
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "修改用户信息失败",
      result: "",
    })
  }
})
//将用户权限升级或者降级
router.put("/users/power/:id", async (req, res) => {
  //解析id
  let { id } = req.params
  //解析请求体数据
  let { type } = req.body
  //编写sql语句
  let sql = `update userinfo set type=${type} where id=${id}`
  try {
    let data = await exec(sql)
    data = await getOne(`select * from userinfo where id=${id}`)
    res.send({
      code: 200,
      message: "修改用户权限成功",
      result: data,
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "修改用户权限失败",
      result: "",
    })
  }
})
//强制用户下线/用户退出登录
router.put("/users/online/:id", async (req, res) => {
  //解析id
  let { id } = req.params
  //编写sql语句
  let sql = `update userinfo set onlinestatus=0 where id=${id}`
  try {
    let data = await exec(sql)
    data = await getOne(`select * from userinfo where id=${id}`)
    res.send({
      code: 200,
      message: "用户下线成功",
      result: data,
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "用户下线失败",
      result: "",
    })
  }
})
//用户注销/删除用户--单个
router.delete("/users/logout/:id", async (req, res) => {
  //解析id
  let { id } = req.params
  //编写sql语句
  let sql = `update userinfo set deleted=1 where id=${id}`
  try {
    let data = await exec(sql)
    //登录状态改为下线
    data = await exec(`update userinfo set onlinestatus=0 where id=${id}`)
    data = await getOne(`select * from userinfo where id=${id}`)
    res.send({
      code: 200,
      message: "用户注销成功",
      result: data,
    })
  } catch (error) {
    res.send({
      code: 200,
      message: "用户注销失败",
      result: "",
    })
  }
})
//注销多个用户
router.delete("/users/logoutmulti", async (req, res) => {
  //解析请求体数据
  let { id } = req.query
  //编写sql语句
  let sql = `update userinfo set deleted=1 where id in (${id})`
  try {
    let data = await exec(sql)
    //将用户状态改为下线
    await exec(`update userinfo set onlinestatus=0 where id in (${id})`)
    data = await getAll(`select * from userinfo where id in (${id})`)
    res.send({
      code: 200,
      message: "注销多个用户成功",
      result: data,
    })
  } catch (error) {
    res.send({
      code: 201,
      message: "注销多个用户失败",
      result: "",
    })
  }
})
//模糊查询用户名
router.get("/users/search", async (req, res) => {
  // 解析参数
  let { keyword, type } = req.query
  let data
  let total
  try {
    if (type) {
      let sql1 = `select * from userinfo where username like '%${keyword}%' and type=${type}`
      data = await getAll(sql1)
      total = data.length
    } else {
      let sql2 = `select * from userinfo where username like '%${keyword} and type=${type}'`
      data = await getAll(sql2)
      total = data.length
    }
    res.send({
      code: 0,
      message: "模糊查询成功",
      result: {
        total,
        data,
      },
    })
  } catch (error) {
    res.send({
      code: 0,
      message: "模糊查询失败",
      result: "",
    })
  }
})
module.exports = router
